package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import net.bytebuddy.utility.RandomString;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备管理Service业务层处理
 *
 * @author gzh
 * @date 2025-10-17
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;


    /*关于 StringRedisTemplate
    StringRedisTemplate是 Spring Data Redis 项目提供的一个模板类，专门用于简化对 Redis 数据库的操作
。它的主要特点包括：
            ​​专门处理字符串​​：它是 RedisTemplate<String, String>的子类，意味着它的键（Key）和值（Value）都默认使用字符串序列化策略
。这非常适用于存储可读的字符串数据。
            ​​丰富的操作方法​​：它提供了 opsForValue()（操作字符串）、opsForHash()（操作哈希）、opsForList()（操作列表）等多种方法，覆盖了 Redis 的主要数据结构
。
        ​​开箱即用​​：在 Spring Boot 项目中，只要添加了 spring-boot-starter-data-redis依赖并正确配置了 Redis 连接信息，Spring Boot 就会自动配置一个 StringRedisTemplate的 Bean，你可以直接通过 @Autowired引入使用
。*/
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }


    /*   从IOT中查询所有的产品数据并放入到Redis中*/
    @Override
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();

        //最多查询50条数据
        request.setLimit(50);
        //从IoT中查询所有的产品数据         client:客户
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("产品同步失败");
        }

        //ProductSummary:产品概要
        List<ProductSummary> products = response.getProducts();
        //放入到Redis中
        redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).set(JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {

        //从redis中查询所有的产品
        String jsonStr = redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).get();
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    @Override
    public void register(DeviceDto dto) {
        //判断设备名称是否重入
        //LambdaQueryWrapper:Lambda 查询包装器
        LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>();

//        设置查询条件：筛选出 device_name字段值与传入参数 dto.getDeviceName()相等的记录
        queryWrapper1.eq(Device::getDeviceName, dto.getDeviceName());

//        执行查询，期望返回最多一条记录。如果存在多条，则会抛出异常
        Device one = this.getOne(queryWrapper1);
        if (one != null) {
            throw new BaseException("设备名称不能重复");
        }


        //判断设备标识是否重入

        LambdaQueryWrapper<Device> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Device::getNodeId, dto.getNodeId());
        one = this.getOne(queryWrapper2);
        if (one != null) {
            throw new BaseException("设备标识不能重复");
        }
        //判断设同一个位置是否有同一种设备
        LambdaQueryWrapper<Device> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(Device::getRemark, dto.getRemark());
        queryWrapper3.eq(Device::getProductKey, dto.getProductKey());
        one = this.getOne(queryWrapper3);
        if (one != null) {
            throw new BaseException("同一个位置不能有同一种设备");
        }

        //先远程调用IOT注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();

//        addDevice.setDeviceId();

        //设备标识码
        // 确保nodeId符合^[a-zA-Z0-9:_-]{1,64}$格式要求
        String nodeId = dto.getNodeId().replaceAll("[^a-zA-Z0-9:_-]", "");
        if (nodeId.length() > 64) {
            nodeId = nodeId.substring(0, 64);
        } else if (nodeId.isEmpty()) {
            // 如果替换后为空，则生成一个随机的nodeId
            nodeId = "device_" + RandomUtil.randomString(10);
        }
        addDevice.setNodeId(nodeId);
        addDevice.setDeviceName(dto.getDeviceName());
        addDevice.setProductId(dto.getProductKey());

        //AuthInfo:身份验证信息
        AuthInfo authInfo = new AuthInfo();
//        String secret = RandomStringUtils.random(32);
        String secret = RandomUtil.randomString(32);
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);
        addDevice.setDescription(dto.getDeviceDescription());
//        addDevice.setGatewayId();
//        addDevice.setAppId();
//        addDevice.setExtensionInfo();
//        addDevice.setShadow();


        request.setBody(addDevice);
        //client:客户
        AddDeviceResponse response = client.addDevice(request);

        if (response.getHttpStatusCode() != 201) {
            throw new BaseException("IOT注册设备失败");
        }
//response:响应
        String deviceId = response.getDeviceId();
        //再保存自己表的数据
        Device device = new Device();
        device.setIotId(deviceId);
        device.setSecret(secret);
        device.setBindingLocation(dto.getBindingLocation() + "");
        device.setLocationType(dto.getLocationType());
        device.setPhysicalLocationType(dto.getPhysicalLocationType());
        device.setDeviceName(dto.getDeviceName());
        device.setProductKey(dto.getProductKey());
        device.setProductName(dto.getProductName());
        device.setDeviceDescription(dto.getDeviceDescription());
//        device.setHaveEntranceGuard();
        device.setNodeId(nodeId);
        device.setRemark(dto.getRemark());

        this.save(device);

    }

    @Override
    public DeviceDetailVo deviceDetail(String iotId) {

        //先查询自己的表

        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        Device one = this.getOne(queryWrapper);
        if (one == null) {
            throw new BaseException("参数有误");
        }

        DeviceDetailVo detailVo = BeanUtil.toBean(one, DeviceDetailVo.class);
        //2再查询IOT
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);

        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("IOT查询失败");
        }

        String activeTimeStr = response.getActiveTime();// 2025-06-01T08:24:24.349Z
        // 把字符串转成LocalDateTime
        LocalDateTime activeTime = null;
        if (activeTimeStr != null && !activeTimeStr.isEmpty()) {
            LocalDateTime parse = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            // DateTimeZoneConverter是今天资料中提供的一个工具类
            activeTime = DateTimeZoneConverter.utcToShanghai(parse);
        }

        detailVo.setActiveTime(activeTime);
        detailVo.setDeviceStatus(response.getStatus());

        return detailVo;
    }

    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {

        //ShowDeviceShadowRequest:显示设备影子请求
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("IOT查询失败");
        }

        List<DeviceShadowData> shadow = response.getShadow();
        DeviceShadowData deviceShadowData = shadow.get(0);
        DeviceShadowProperties reported = deviceShadowData.getReported();

        String eventTimeStr = reported.getEventTime();// 2025-06-01T08:24:24.349Z
        // 把字符串转成LocalDateTime
        LocalDateTime eventTime = null;
        if (eventTimeStr != null && !eventTimeStr.isEmpty()) {
            LocalDateTime parse = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            // DateTimeZoneConverter是今天资料中提供的一个工具类
            eventTime = DateTimeZoneConverter.utcToShanghai(parse);
        }

        List<DeviceDataVo> list = new ArrayList<DeviceDataVo>();
        //getProperties:获取属性
        LinkedHashMap<String, Object> linkedHashMap = (LinkedHashMap) reported.getProperties();
        for (String key : linkedHashMap.keySet()) {
            DeviceDataVo deviceDataVo = new DeviceDataVo();
            deviceDataVo.setFunctionId(key);
            deviceDataVo.setEventTime(eventTime);
            deviceDataVo.setValue(linkedHashMap.get(key));
            list.add(deviceDataVo);


        }
        return list;
    }

    @Override
    public void updateDevice(DeviceDto deviceDto) {
        // 先从本地数据库中查询设备信息
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getId, deviceDto.getId());
        Device device = this.getOne(queryWrapper);

        if (device == null) {
            throw new BaseException("设备不存在");
        }

        // 调用华为云IoTDA接口更新设备
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(device.getIotId());

        UpdateDevice updateDevice = new UpdateDevice();
        updateDevice.setDeviceName(deviceDto.getDeviceName());
        updateDevice.setDescription(deviceDto.getDeviceDescription());

        request.setBody(updateDevice);

        try {
            UpdateDeviceResponse response = client.updateDevice(request);
            if (response.getHttpStatusCode() != 200) {
                throw new BaseException("IOT更新设备失败");
            }
        } catch (ConnectionException e) {
            throw new BaseException("连接华为云IoTDA服务失败: " + e.getMessage());
        } catch (RequestTimeoutException e) {
            throw new BaseException("请求华为云IoTDA服务超时: " + e.getMessage());
        } catch (ServiceResponseException e) {
            throw new BaseException("华为云IoTDA服务响应异常: " + e.getMessage());
        }

        // 更新本地数据库中的设备记录
        device.setDeviceName(deviceDto.getDeviceName());
        device.setDeviceDescription(deviceDto.getDeviceDescription());
        device.setLocationType(deviceDto.getLocationType());
        device.setBindingLocation(deviceDto.getBindingLocation() + "");
        device.setPhysicalLocationType(deviceDto.getPhysicalLocationType());
        device.setRemark(deviceDto.getRemark());
        device.setProductKey(deviceDto.getProductKey());
        device.setProductName(deviceDto.getProductName());

        this.updateById(device);
    }

    @Override
    public List<DeviceDataVo> deleteDevice(String iotId) {
        // 先从本地数据库中查询设备信息
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        Device device = this.getOne(queryWrapper);

        if (device == null) {
            throw new BaseException("设备不存在");
        }

        // 调用华为云IoTDA接口删除设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);

        try {
            DeleteDeviceResponse response = client.deleteDevice(request);
            if (response.getHttpStatusCode() != 204) {
                throw new BaseException("IOT删除设备失败");
            }
        } catch (ConnectionException e) {
            throw new BaseException("连接华为云IoTDA服务失败: " + e.getMessage());
        } catch (RequestTimeoutException e) {
            throw new BaseException("请求华为云IoTDA服务超时: " + e.getMessage());
        } catch (ServiceResponseException e) {
            throw new BaseException("华为云IoTDA服务响应异常: " + e.getMessage());
        }

        // 从本地数据库中删除设备记录
        this.remove(queryWrapper);

        // 返回空列表，与接口定义保持一致
        return new ArrayList<>();
    }


    //远程调用IOT方法
    @Override
    public AjaxResult querySProductById(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct(request);

        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("IOT查询产品失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        return AjaxResult.success(serviceCapabilities);
    }

    /**
     * 查询产品详情
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        //参数校验
        if(StringUtils.isEmpty(productKey)){
            throw new BaseException("请输入正确的参数");
        }
        //调用华为云物联网接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = client.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }
        //判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)){
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }
}